package com.pjmike.server.netty;


import com.pjmike.common.protocol.RpcDecoder;
import com.pjmike.common.protocol.RpcEncoder;
import com.pjmike.common.protocol.RpcRequest;
import com.pjmike.common.protocol.RpcResponse;
import com.pjmike.common.protocol.serialize.JSONSerializer;
import com.pjmike.server.handler.ServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PreDestroy;

/**
 * @description:
 * @author: pjmike
 * @create: 2019/04/07 17:21
 */
@Configuration
@Slf4j
public class NettyServer {

    /**
     * 请求大致过程：
     * 创建 EventLoopGroup。
     * 创建 ServerBootstrap。
     * 指定所使用的 NIO 传输 Channel。
     * 使用指定的端口设置套接字地址。
     * 添加一个 ServerHandler 到 Channel 的 ChannelPipeline。
     * 异步地绑定服务器；调用 sync() 方法阻塞等待直到绑定完成。
     * 获取 Channel 的 CloseFuture，并且阻塞当前线程直到它完成。
     * 关闭 EventLoopGroup，释放所有的资源。
     */
    private EventLoopGroup boss = null;
    private EventLoopGroup worker = null;

    @Autowired
    private ServerHandler serverHandler;
//    @Override
//    public void afterPropertiesSet() throws Exception {
////        ServiceRegistry registry = new ZkServiceRegistry("127.0.0.1:2181");
//        start();
//    }

    public void start() throws Exception {
        //(1)创建EventLoopGroup
        boss = new NioEventLoopGroup();
        worker = new NioEventLoopGroup();
        //(2)创建ServerBootstrap
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(boss, worker)
                //(3)指定所使用得NIO传输得channel
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 1024)
                //(4)添加一个serverHandler到Channel的channelPipeline
                //(4)添加序列化和反序列化到Channel的channelPipeline
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new LengthFieldBasedFrameDecoder(65535, 0, 4));
                        pipeline.addLast(new RpcEncoder(RpcResponse.class, new JSONSerializer()));
                        pipeline.addLast(new RpcDecoder(RpcRequest.class, new JSONSerializer()));
                        pipeline.addLast(serverHandler);

                    }
                });
        //(5) 异步得绑定服务器；调用sync()方法阻塞等待直到绑定完成
        bind(serverBootstrap, 8888);
//        registry.registry("127.0.0.1:8888");
    }

    /**
     * 如果端口绑定失败，端口数+1,重新绑定
     *
     * @param serverBootstrap
     * @param port
     */
    public void bind(final ServerBootstrap serverBootstrap,int port) {
        ChannelFuture channelFuture = serverBootstrap.bind(port).addListener(future -> {
            if (future.isSuccess()) {
                log.info("端口[ {} ] 绑定成功", port);
            } else {
                log.error("端口[ {} ] 绑定失败", port);
                bind(serverBootstrap, port + 1);
            }
        });
        log.info("Server start listen at={}",port);
        try {
            boolean start = channelFuture.isDone();
            log.info("start",start);
            //(6)获取Channel得CloseFuture，并且阻塞当前线程直到它完成
            channelFuture.channel().closeFuture().sync();
            boolean end = channelFuture.isDone();
            log.info("end",end);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("执行到这里={}",port);
    }

    /**
     * 关闭EventLoopGroup资源
     * @throws InterruptedException
     */
    @PreDestroy
    public void destory() throws InterruptedException {
        boss.shutdownGracefully().sync();
        worker.shutdownGracefully().sync();
        log.info("关闭Netty");
    }
}
